package com.wangcp.springboottenant.config;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.util.cnfexpression.MultipleExpression;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class MyTenantHandler implements TenantLineHandler {
    /**
     * 租户id
     * @return
     */
    @Override
    public Expression getTenantId() {
        String tableName = GlobalVarManager.getGlobalVars();
        String tenantId = "10001";
        if(tableName.equals("users")){
            List<Expression> childlist = new ArrayList<>();
            childlist.add(new StringValue(tenantId));
            childlist.add(new StringValue("10002"));
            MultipleExpression multipleExpression = new MultipleExpression(childlist) {
                @Override
                public String getStringExpression() {
                    return ",";
                }
            };
            return multipleExpression;
        }else{
            return new LongValue(tenantId);
        }
    }

    /**
     * 根据表名判断是否忽略拼接多租户条件
     * 默认为false，不忽略
     * @param tableName
     * @return
     */
    @Override
    public boolean ignoreTable(String tableName) {
        // 此处将表名放入线程副本中
        GlobalVarManager.setGlobalVal(tableName);
        System.out.println(tableName);
        return false;
    }
}
